package org.lyh.org.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.lyh.base.util.Result;
import org.lyh.org.domain.Department;
import org.lyh.org.query.DepartmentQuery;
import org.lyh.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/department")
@Api(tags = "部门管理")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;
    @GetMapping
    @ApiOperation("查询所有部门")
    Result getDeptList(){
        try {
            return Result.success(departmentService.queryList());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("后台未知错误！");
        }

    }
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询一个部门")
    Result getDeptOne(@PathVariable("id") Long id){
        Department department = departmentService.queryOne(id);
        return department==null ? Result.error("查询的部门不存在！"):Result.success(department);
    }
    @PutMapping
    @ApiOperation("更新或新增部门")
    Result updateOrInsertDept(@RequestBody Department department){
        if (department.getId()!=null){
            departmentService.updateOne(department);
            department.setUpdateTime(new Date());
        }else {
            departmentService.addOne(department);
            department.setCreateTime(new Date());
        }
        //处理dir_path和创建时间或更新时间
        departmentService.fixDirPathAndDate(department);
        return Result.success();
    }
    @DeleteMapping("/{id}")
    @ApiOperation("根据ID删除部门")
    Result deleteDept(@PathVariable("id") Long id){
        try {
            departmentService.deleteById(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("部门新增失败！");
        }

    }
    @ApiOperation("根据ids批量删除部门")
    @PatchMapping
    Result batchDelete(@RequestBody List<Long> ids){
        try {
            departmentService.batchDelete(ids);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量删除出错！");
        }
    }
    //高级查询及分页查询
    @ApiOperation("高级查询及分页查询")
    @PostMapping("/query")
    Result query(@RequestBody DepartmentQuery dto){
        try {
            return Result.success(departmentService.queryPage(dto));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询出错！");
        }
    }
    //获取部门树
    @ApiOperation("获取部门树")
    @GetMapping("/tree")
    Result getDeptTree(){
        try {
            return Result.success(departmentService.queryTree());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询出错！");
        }
    }
}
